package me.zk.practice1.list;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: zhang kai
 * @Date: 2022/01/01
 * @Description:
 */
public class Solution2 {
    public void moveZeroes(int[] nums) {
        int n = nums.length, left = 0, right = 0;
        while (right < n) {
            if (nums[right] != 0) {
                swap(nums, left, right);
                left++;
            }
            right++;
        }
    }

    public void swap(int[] nums, int left, int right) {
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
    public int[] twoSum(int[] numbers, int target) {
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for (int i = 0; i < numbers.length; i++) {
            if(!map.containsKey(target - numbers[i])) {
                map.put(numbers[i], i);
            } else {
                return new int[]{map.get(target - numbers[i]),i};
            }

        }

        return null;
    }
    public int[] twoSum2(int[] numbers, int target) {
        int left = 0;
        int right = numbers.length-1;
        while (left < right) {
            int sum = numbers[left] + numbers[right];
            if (sum == target) {
                return new int[]{left+1, right+1};
            } else if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[]{-1,-1};
    }

    public String reverseWords(String s) {
      int i = 0;
      StringBuffer sb = new StringBuffer();
      while (i < s.length()) {
          int start = i;
          while (i < s.length() &&  s.charAt(i) != ' ') {
              i++;
          }
          for (int j = start; j < i; j++) {
              sb.append(s.charAt(i - j - 1 + start));
          }
          while (i < s.length() && s.charAt(i) == ' ') {
              i++;
              sb.append(' ');
          }
       }
      return sb.toString();
    }
    public char[] reverseString(char[] s) {
        int left = 0;
        int right = s.length - 1;
        while(left < right) {
            swap(s, left, right);
            left++;
            right--;
        }
        return s;
    }
    public void swap(char[] s, int left, int right) {
        char temp = s[left];
        s[left] = s[right];
        s[right] = temp;
    }
}
